package TopologyService;

import java.util.ArrayList;

public class Topology {
	
	private int nextNodeID;
	private String nextNodeIP;
	private int nextNodePort;
	
	private int prevNodeID;
	private String prevNodeIP;
	private int prevNodePort;
	
	private int myNodeID;
	private String myNodeIP;
	private int myNodePort;
	
	private int maxNodes;
	private ArrayList<String[]> nodeMap;
	
	
	public Topology(int myNodeID, ArrayList<String[]> nodeMap){
		this.myNodeID = myNodeID;
		myNodeIP = nodeMap.get(myNodeID)[0];
		this.myNodePort =  Integer.parseInt(nodeMap.get(myNodeID)[1]);
		this.nodeMap = nodeMap;
		maxNodes = nodeMap.size();
	}
	
	public synchronized void setNext(int nodeID){
		System.out.println("Process " + myID() + " setting next node to " +nodeID);
		nextNodeID = nodeID;
		nextNodeIP = nodeMap.get(nodeID)[0];
		nextNodePort = Integer.parseInt(nodeMap.get(nodeID)[1]);
	}
	
	public synchronized void setPrev(int nodeID){
		System.out.println("Process " + myID() + " setting prev node to " +nodeID);
		prevNodeID = nodeID;
		prevNodeIP = nodeMap.get(nodeID)[0];
		prevNodePort = Integer.parseInt(nodeMap.get(nodeID)[1]);
	}
	
	public synchronized void failureDetected(int nodeID){
		System.out.println("Process " + myNodeID + " detected faulty node " + nodeID );
		
		if(nodeID == prevNodeID){
			prevNodeID = prevNodeID - 1;
			if(prevNodeID < 0){
				prevNodeID = nodeMap.size() - 1;
			}
			prevNodeIP = nodeMap.get(prevNodeID)[0];
			prevNodePort = Integer.parseInt(nodeMap.get(prevNodeID)[1]);
			System.out.println("Process " + myNodeID + " changing prev from " + nodeID + " to " + prevNodeID);
		}
		else if(nodeID == nextNodeID){
			nextNodeID = (nextNodeID + 1) % maxNodes;
			nextNodeIP = nodeMap.get(nextNodeID)[0];
			nextNodePort = Integer.parseInt(nodeMap.get(nextNodeID)[1]);
			System.out.println("Process " + myNodeID + " changing next from " + nodeID + " to " + nextNodeID);
		}
		else{
			System.out.println("Process " + myNodeID + " not connected to faulty node " + nodeID );
		}	
	}
	
	public synchronized String getNextIP(){
		return this.nextNodeIP;
	}
	
	public synchronized int getNextPort(){
		return this.nextNodePort;
	}
	
	public synchronized int getNextID(){
		return this.nextNodeID;
	}
	
	public synchronized String getPrevIP(){
		return this.prevNodeIP;
	}
	
	public synchronized int getPrevPort(){
		return this.prevNodePort;
	}
	
	public synchronized int getPrevID(){
		return this.prevNodeID;
	}
	
	public int myID(){
		return this.myNodeID;
	}
	

}
